package com.example.moonshine.baidumap.View.Activity;

/**
 * Created by User on 2017/11/27.
 */

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Looper;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;


import com.example.moonshine.baidumap.Entity.loginHttpResultData;
import com.example.moonshine.baidumap.R;
import com.example.moonshine.baidumap.Service.LoginService;
import com.example.moonshine.baidumap.Util.DataDBHepler;
import com.example.moonshine.baidumap.Util.HttpUtil;

import com.example.moonshine.baidumap.Util.UrlHttpData;
import com.example.moonshine.baidumap.Util.publicUtil;
import com.github.zackratos.ultimatebar.UltimateBar;
import com.google.gson.Gson;

import static android.content.ContentValues.TAG;

/**
 * Created by Administrator on 2017/11/7 0007.
 */

public class LoginActivity extends Activity {


    EditText usernameEt;
    EditText passwordEt;
    Button loginButton;
    DataDBHepler dbHepler;
    String resultStatusCode=null;
    String username = null;
    String password = null;
    final publicUtil publicUtil = new publicUtil();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        //判断网络工具
       if (NetWorkUtils.isNetworkConnected(getBaseContext()))
       {
       }else {
           Toast.makeText(this, "网络未连接", Toast.LENGTH_SHORT).show();
       }
        ViewLayout();
        try {
            username=publicUtil.getUserInfo(getBaseContext(),"username","login");
            password=publicUtil.getUserInfo(getBaseContext(),"password","login");
        } catch (Exception e) {
            e.printStackTrace();
        }
        usernameEt.setCursorVisible(false);
        passwordEt.setCursorVisible(false);
        usernameEt.setText(username);
        passwordEt.setText(password);
        usernameEt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                usernameEt.setCursorVisible(true);
            }
        });
        passwordEt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                passwordEt.setCursorVisible(true);
            }
        });

    }

    //控件初始化
    public void ViewLayout() {
        loginButton = findViewById(R.id.login_btn);
        usernameEt = findViewById(R.id.login_user);
        passwordEt = findViewById(R.id.login_pass);
    }

//    public void init() {
//        Intent intent = getIntent();
//        url = intent.getStringExtra("url");
//        try {
//            if (url.equals("null")) {
//                Log.i(TAG, "已经为最新版本");
//
//            } else {
//                Log.i(TAG, "该下载链接为:" + url);
//                showDialog();
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//    }

//    public void showDialog() {
//        downloadUtils = new DownloadUtil(LoginActivity.this);
//        final UpdateDialog Dialog = new UpdateDialog(LoginActivity.this);
//        Dialog.setTitle("消息提示");
//        Dialog.setMessage("发现新版本，是否更新?");
//        Dialog.setYesOnclickListener("确定", new UpdateDialog.onYesOnclickListener() {
//            @Override
//            public void onYesClick() {
//                downloadUtils.downloadAPK(url, "apk");
//                Dialog.dismiss();
//            }
//        });
//        Dialog.setNoOnclickListener("取消", new UpdateDialog.onNoOnclickListener() {
//            @Override
//            public void onNoClick() {
//                Dialog.dismiss();
//            }
//        });
//        Dialog.show();
//    }

    @Override
    protected void onStart() {
        // 设置状态栏颜色
        UltimateBar.newColorBuilder()
                .statusColor(Color.parseColor("#003768"))       // 状态栏颜色
                .statusDepth(50)                // 状态栏颜色深度
                .build(this)
                .apply();

        // 判断GPS权限
        if (ActivityCompat.checkSelfPermission(getBaseContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
//            // TODO: Consider calling
//            //    ActivityCompat#requestPermissions
//            // here to request the missing permissions, and then overriding
//            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
//            //                                          int[] grantResults)
//            // to handle the case where the user grants the permission. See the documentation
//            // for ActivityCompat#requestPermissions for more details.
            ActivityCompat.requestPermissions(LoginActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},2);
        }

        // 点击事件
        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Looper.prepare();
                        try {

                            if(usernameEt.getText().toString().equals("")||passwordEt.getText().toString().equals(""))
                            {
                                publicUtil.ToastShow(LoginActivity.this,"用户名或密码不能为空");
                            }
                            resultStatusCode = getUrlCodeLogin(usernameEt.getText().toString(),passwordEt.getText().toString());
                            Log.i(TAG, "run: " +resultStatusCode);

                            if (resultStatusCode.equals("14")) {
                                LoginService loginService = new LoginService();
                                loginService.saveUserInfo(getBaseContext(),usernameEt.getText().toString(),passwordEt.getText().toString());

                                publicUtil.ToastShow(getBaseContext(),"登陆成功");

                                publicUtil.LogShow("登陆成功",usernameEt.getText().toString());

                                Intent intent = new Intent();
                                intent.setClass(LoginActivity.this, MainActivity.class);
                                startActivity(intent);
                                finish();
                            } else if (resultStatusCode.equals("12")) {
                               publicUtil.ToastShow(getBaseContext(),"登陆失败");//提示用户登录失败
                            } else if (resultStatusCode.equals("13")) {
                                publicUtil.ToastShow(getBaseContext(),"登录失败，用户已存在不能重复登录");
//
                            } else {
                                publicUtil.ToastShow(getBaseContext(),"登录失败，用户名或密码错误");
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        Looper.loop();
                    }
                }).start();
            }
        });

        super.onStart();
    }
    //网络请求
    public String getUrlCodeLogin(String username,String password){
        Gson gson = new Gson();
        UrlHttpData urlHttpData = new UrlHttpData(); //获取URL
        HttpUtil httpUtil = new HttpUtil(); // 访问请求
        String resData = httpUtil.GetPostLogin(username,password,urlHttpData.loginUrl);
        loginHttpResultData resultData = gson.fromJson(resData,loginHttpResultData.class);
        String token = resultData.getToken();
        publicUtil.saveInfo(getBaseContext(),"token",token,"token");
        return resultData.getMsg();
    }

}